<template>
  <ul class="tabs-menu">
    <li :class="[{ active: currentPath(item.path) }]" v-for="item in state.routerList" :key="item.path" @click="handlerMenu(item)">
      <span>{{ item?.meta?.title }}</span>
    </li>
  </ul>
</template>
<script setup>
  import { computed, reactive, watch } from "vue"
  import { useRouter } from "vue-router"
  /**
   * route
   */
  const router = useRouter()
  /**
   * state
   */
  const state = reactive({
    routerList: [],
  })

  /**
   * 获取最后一层路由的第1个子级
   */
  const getLastRouerChildren = (routerInfo) => routerInfo?.children?.[0]

  /**
   * handlerMenu
   */
  const handlerMenu = (val) => {
    // 是否有缓存path
    const routerInfo = router.getRoutes().filter((item) => item.path === val.path)[0]
    let keepAlivePath = null
    if (routerInfo?.meta && routerInfo.meta.keepAlivePath) {
      keepAlivePath = routerInfo.meta.keepAlivePath
    }
    // 路由
    const path = keepAlivePath || getLastRouerChildren(routerInfo).path
    router.push({ path: val.path })
  }

  /**
   * 获取子级路由
   */
  const getChildrenRouter = () => {
    const routers = router.currentRoute.value?.matched?.[0]
    state.routerList = routers?.children || []
  }

  /**
   * 当前路由高亮
   */
  const currentPath = computed(() => {
    return (path) => router.currentRoute.value?.matched?.[1]?.path === path
  })

  watch(
    () => router.currentRoute.value,
    () => {
      getChildrenRouter()
    },
    {
      immediate: true,
    }
  )
</script>
<style lang="scss" scoped>
  .tabs-menu {
    position: relative;
    display: flex;
    align-items: center;
    padding-left: 20px;
    li {
      position: relative;
      height: var(--n-header-menu-height);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      cursor: pointer;
      color: var(--n-black-light-1);
      + li {
        margin-left: 32px;
      }
    }
    span {
      white-space: nowrap;
    }
    .active {
      color: $primary;
      &::after {
        content: "";
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        border-bottom: 2px solid $primary;
      }
    }
  }
</style>
